import { Provide } from '@midwayjs/decorator';
// import {} from '@midwayjs/orm';
import { Config } from '@midwayjs/decorator';
import dayjs from 'dayjs';
import fs from 'fs';
// import os from 'os';
import { join } from 'path';
import { BaseService } from '@core/index';

@Provide()
export class FileService extends BaseService {
  @Config('upload')
  configUpload;

  /**
   * 图片上传
   * @param upload
   */
  async uploadBase64() {}

  /**
   * 图片上传
   * @param uploadForm
   */
  async uploadForm(files, fields) {
    const file = files[0];
    const filePath = `public/uploads/${dayjs().format('YYYYMMDD')}`;
    const dirFileName = `${dayjs().format('YYYYMMDDHHmmss')}.png`;

    const target = join(this.app.getAppDir(), filePath, dirFileName);
    const dirPath = join(this.app.getAppDir(), filePath);
    if (!fs.existsSync(dirPath)) {
      fs.mkdirSync(dirPath);
    }
    await mv(file.data, target);

    // console.log('@Files', files);
    // console.log('@dirPath', dirPath);
    // console.log('this.configUpload', this.configUpload.domain);
    return `${this.configUpload.domain}/${filePath}/${dirFileName}`;
    // return this.configUpload.domain + '/' + filePath + '/' + dirFileName;
  }
}
// 解决windows -4037问题
const mv = async (sourcePath, destPath) => {
  try {
    await fs.promises.rename(sourcePath, destPath);
  } catch (error) {
    if (error.code === 'EXDEV') {
      const readStream = fs.createReadStream(sourcePath);
      const writeStream = fs.createWriteStream(destPath);
      return new Promise<void>((resolve, reject) => {
        readStream.pipe(writeStream);
        readStream.on('end', onClose);
        readStream.on('error', onError);
        async function onClose() {
          await fs.promises.unlink(sourcePath);
          resolve();
        }
        function onError(err) {
          console.error(`File write failed with message: ${err.message}`);
          writeStream.close();
          reject(err);
        }
      });
    }

    throw error;
  }
};
